/*
 * Copyright (c) 2003-2009 jMonkeyEngine
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of 'jMonkeyEngine' nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.elhakimz.matra;

import com.elhakimz.matra.actor.Actor;
import com.elhakimz.matra.scene.SceneManager;
import com.elhakimz.matra.ui.InputManager;
import com.elhakimz.matra.ui.window.TracksWindow;
import com.elhakimz.matra.util.GlobalVars;
import com.elhakimz.matra.util.GeoUtil;
import com.jme.app.SimpleGame;
import com.jme.input.AbsoluteMouse;
import com.jme.input.InputHandler;
import com.jme.input.KeyboardLookHandler;
import com.jme.input.MouseInput;
import com.jme.math.Vector3f;
import com.jme.renderer.Renderer;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.system.DisplaySystem;
import com.jmex.awt.swingui.JMEDesktop;
import com.jmex.bui.*;
import com.jmex.bui.event.DialogListener;
import com.jmex.bui.headlessWindows.DialogBoxUtil;
import com.jmex.bui.layout.*;
import com.jmex.bui.background.TintedBackground;

import java.util.logging.Logger;


public class MatraSystem extends SimpleGame {
    private static final Logger logger = Logger.getLogger(MatraSystem.class
            .getName());

    private JMEDesktop jmeDesktop;
    private KeyboardLookHandler lookHandler;
    private SceneManager sceneManager;
    InputManager inputManager = new InputManager();
    public static DisplaySystem disp;

    public MatraSystem() {
    }

    protected void simpleUpdate() {
  
    }

    public static void main( String[] args ) throws Exception {
        MatraSystem game = new MatraSystem();
        game.setConfigShowMode( ConfigShowMode.AlwaysShow );
        game.start();
    }

    /**
     * Called near end of initGame(). Must be defined by derived classes.
     */
    protected void simpleInitGame() {
        disp=display;
        display.setTitle( "MATRA 001" );
        BuiSystem.init(new PolledRootNode(timer, input), "/rsrc/style2.bss");
        rootNode.attachChild(BuiSystem.getRootNode());
        
        initInput();

        
        rootNode.attachChild( GlobalVars.desktopNode );
        rootNode.setCullHint( Spatial.CullHint.Never );
        initScene();
        initActors();
        fullScreen();
        createDesktop();


       // createCustomCursor();

        // for experimenting with events:
//        JFrame frame = new JFrame();
//
//        frame.pack();
//        frame.setVisible( true );
//        Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener() {
//            public void eventDispatched( AWTEvent event ) {
//                logger.info( event );
//            }
//        }, 0xFFFFFFFFFFFFFFl );
//        JButton button = new JButton( "test" );
//        button.setMnemonic( 't' );
//        frame.getContentPane().add( button );
//        button.addActionListener( new ActionListener() {
//            public void actionPerformed( ActionEvent e ) {
//                logger.info( "now" );
//            }
//        } );

    }

    private void initInput(){
         // move the 'default' keys (debug normals, toggle lighting, etc.) to a separated input handler

        super.input = inputManager;

		display.setTitle("Orbit Camera");
		MouseInput.get().setCursorVisible(true);

		cam.setLocation(new Vector3f(100, 100, -200));
		cam.update();
  	    inputManager.setup(cam);
		inputManager.getOrbit().setWheelDirection(true);
		// The target position is the point the camera orbits around
		inputManager.getOrbit().setTargetPosition(new Vector3f(), true);

		GlobalVars.pickNode = new Node();
		rootNode.attachChild(GlobalVars.pickNode);

		// Set the node used when picking
		inputManager.getCameraFocus().setNode(GlobalVars.pickNode);

        InputHandler handlerForDefaultKeyActions = input;
        // remove the first person nested handlers
        handlerForDefaultKeyActions.removeAllFromAttachedHandlers();
        // create a new handler for our input
        input = new InputHandler();
        // add the default handler as a child
        input.addToAttachedHandlers( handlerForDefaultKeyActions );
        // create another look handler
        lookHandler = new KeyboardLookHandler( cam, 50, 1 );
        // and nest it
        input.addToAttachedHandlers( lookHandler );
        MouseInput.get().setCursorVisible( true );
    }


    private void initScene(){
       this.sceneManager= new SceneManager(rootNode, cam, lightState);
    }

    private void initActors(){
        Actor act2 = new Actor("blue-2","blue","resources/matra/model/boat.3ds");
        act2.activate().setPos(100,10,0);

        Actor act1 = new Actor("blue-3","blue","resources/matra/model/boat.3ds");
        act1.activate()
                .setPos(0,0,0);

        Vector3f[] points = new Vector3f[5];
        points[0]= GeoUtil.GV3f(0,0,0);
        points[1]= GeoUtil.GV3f(200,20,0);
        points[2]= GeoUtil.GV3f(200,200,0);
        points[3]= GeoUtil.GV3f(20,200,0);
        points[4]= GeoUtil.GV3f(0,0,0);


        act1.setSpeed(0.001f)
                .followWaypoints(points);



        Actor act3 = new Actor("blue-4","blue","resources/matra/model/sukhoi.3ds");
        act3.activate().setPos(20,20,10);

         points = new Vector3f[4];
        points[0]= GeoUtil.GV3f(20,20,10);
        points[1]= GeoUtil.GV3f(200,20,20);
        points[2]= GeoUtil.GV3f(200,200,30);
        points[3]= GeoUtil.GV3f(20,200,40);
        act3.setSpeed(0.03f)
                .followWaypoints(points);

        Actor act4 = new Actor("blue-5","blue","resources/matra/model/sukhoi.3ds");
        act4.activate()
                .setPos(-20,-20,10);


        points = new Vector3f[4];
        points[0]= GeoUtil.GV3f(20,20,20);
        points[1]= GeoUtil.GV3f(200,20,20);
        points[2]= GeoUtil.GV3f(200,200,30);
        points[3]= GeoUtil.GV3f(20,200,40);

        act4.setSpeed(0.05f)
                .followWaypoints(points);

    }


    private void fullScreen() {
        final DisplaySystem display = DisplaySystem.getDisplaySystem();

        GlobalVars.desktopNode.getLocalRotation().set( 0, 0, 0, 1 );
        GlobalVars.desktopNode.getLocalTranslation().set( display.getWidth() / 2, display.getHeight() / 2, 0 );
        GlobalVars.desktopNode.getLocalScale().set( 1, 1, 1 );
        GlobalVars.desktopNode.setRenderQueueMode( Renderer.QUEUE_ORTHO );
        GlobalVars.desktopNode.setCullHint( Spatial.CullHint.Never );
    }

    private boolean moreStuffCreated;

    private AbsoluteMouse cursor;

    BButton bButton;
    protected void createDesktop(){

        BDecoratedWindow window1 = new BDecoratedWindow(BuiSystem.getStyle(), "");
       BuiSystem.getRootNode().addWindow(window1);
          window1.setBounds(5, display.getHeight()-45, 200, 40);
           window1.setBackground(0,new TintedBackground(ColorRGBA.lightGray));
          window1.setAlpha(0.75f);

        final GroupLayout glay = GroupLayout.makeHStretch();
        glay.setGap(2);
        BContainer cont = new BContainer(glay);
        BButton bb = new BButton("DTBS");
        
        cont.add(bb);
        cont.add(new BButton("TACT"));
        cont.add(new BButton("MSGS"));

        window1.add(cont);        



       TracksWindow twindow = new TracksWindow(display);
        twindow.create();


 

       // mw.getComponentArea().setLayoutManager(new AbsoluteLayout());
        //mw.getComponentArea().add(bButton);
        BDialogBox box = DialogBoxUtil.createInfoDialogBox("dialogWindow1", "Welcome To MATRA");
        box.setDialogListener(new DialogListener() {

            public void responseAvailable(UserResponse response, BComponent source) {
                System.out.println(response.toString());
            }
        });
                                

    }


    protected void cleanup() {
        if ( jmeDesktop != null ) {
            jmeDesktop.dispose();
        }
        super.cleanup();
    }
}
